//
//  BIDHeaderViewForMainView.m
//  ShanDongPCC
//
//  Created by mal on 16/8/29.
//  Copyright © 2016年 mal. All rights reserved.
//

#import "BIDHeaderViewForHomeView.h"
#import "BIDCollectionCellForHeaderView.h"
#import "BIDDataCommunication.h"
#import "AppDelegate+StaticMethod.h"
#import <SDWebImage/UIImageView+WebCache.h>

//顶部图片轮播
static NSString *advertisementURL = @"advertisementAndroid/list.action";

@interface BIDHeaderViewForHomeView()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    NSArray *_dataSourceArr;
    NSTimer *_timer;
    NSInteger _curPage;
    NSInteger _slideImgCount;
}
@end

@implementation BIDHeaderViewForHomeView
@synthesize delegate;

- (void)awakeFromNib
{
    [super awakeFromNib];
    //
    _curPage = 0;
    _slideImgCount = 0;
    _dataSourceArr = [[NSArray alloc] init];
    [_collectionView registerClass:[BIDCollectionCellForHeaderView class] forCellWithReuseIdentifier:@"identifier"];
    [self createTimer];
    [self getDataSource];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setItemSize:CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
    [flowLayout setMinimumLineSpacing:0];
    //[flowLayout setMinimumInteritemSpacing:0];
    [_collectionView setCollectionViewLayout:flowLayout];
    _collectionView.pagingEnabled = YES;
    _collectionView.bounces = NO;
}
- (void)getDataSource
{
    BIDDataCommunication *dc = [[BIDDataCommunication alloc] init];
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], advertisementURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"page=%@&rows=%@", @1, @5];
    [dc getDataFromNet:strRequestURL postValue:strPost completionHandler:^(id obj, NSError *err){
        if(obj && !err)
        {
            if([obj isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *responseDic = (NSDictionary*)obj;
                NSNumber *res = responseDic[@"head"][@"success"];
                if([res intValue] == 1)
                {
                    NSArray *bodyArr = responseDic[@"body"][@"rows"];
                    _dataSourceArr = [[NSArray alloc] initWithArray:bodyArr];
                    _slideImgCount = bodyArr.count;
                    _pageCtrl.numberOfPages = _slideImgCount;
                    [_collectionView reloadData];
                }
            }
        }
        else
        {
        }
    }];
}
/**
 *  创建计时器,用来实现自动轮播
 */
- (void)createTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(nextPic) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)nextPic
{
    if(_slideImgCount>0)
    {
        _curPage++;
        if(_curPage == _slideImgCount)
        {
            _curPage = 0;
        }
        _pageCtrl.currentPage = _curPage;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_curPage inSection:0];
        [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        //[_collectionView setContentOffset:CGPointMake(_curPage*CGRectGetWidth(self.frame), 0) animated:YES];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer invalidate];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"%ld", page);
    _curPage = page;
    [_pageCtrl setCurrentPage:page];
    [self createTimer];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = nil;
    NSUInteger row = indexPath.row;
    BIDCollectionCellForHeaderView *headerCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    NSDictionary *dic = _dataSourceArr[row];
    NSString *strImgDownloadURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"slideimg"]];
    [headerCell.imgView setImageWithURL:[NSURL URLWithString:strImgDownloadURL] placeholderImage:[UIImage imageNamed:@"slide_placeholder.png"]];
    cell = headerCell;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", indexPath.row);
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[row];
    [delegate loadContentWithAdvertisementID:dic[@"id"]];
}

@end
